<template>
  <div class="main">
    <div>
      <log-add
        v-if="!isSeas && canCreateFollowRecord"
        :id="id"
        ref="logAdd"
        v-loading="sendLoading"
        :crm-type="crmType"
        class="log-add"
        :props="{
          showRelativeAdd: crmType !== 'leads'
        }"
        :crm-relative-props="crmRelativeProps"
        @send="sendLog" />

      <div :class="{'is-top':isSeas}" class="log">
        <flexbox class="log__filter">
          <flexbox class="filter-left">
            <span class="filter-text">
              {{ $t('crm.components.d4fc7b871a031071a1382d8fbca2c9c1') }}
            </span>
            <el-button
              v-if="showRecord"
              size="medium"
              :class="{ 'el-button--selected': filterValue.queryType === 1 }"
              @click="handleSelectClick(1)">
              {{ $t('crm.components.7516460944cbf7d8c2c4bf21a3532609') }}
            </el-button>
            <el-button
              size="medium"
              :class="{ 'el-button--selected': filterValue.queryType === 2 }"
              @click="handleSelectClick(2)">
              {{ $t('crm.components.85e15c28971b084dd644bb1f5b190670',{1: typeName }) }}
            </el-button>
          </flexbox>
          <flexbox-item class="filter-right">
            <el-popover
              v-model="filterPopoverVisible"
              width="300"
              placement="bottom-end"
              trigger="click">
              <div class="filter-popover">
                <div class="filter-popover__body">
                  <div class="filter-item">
                    <el-input
                      ref="activitySearchInput"
                      v-model.trim="filterValue.search"
                      :placeholder="$t('crm.components.0ffa0523be4f731d6a35273ac8605eb3')"
                      prefix-icon="el-icon-search" />
                  </div>
                  <!-- 动态筛选 -->
                  <template
                    v-if="filterValue.queryType === 2 && typeList && typeList.length > 1">
                    <div class="filter-item">
                      <div class="filter-item__label">
                        {{ $t('crm.components.2a7d920fae7fe45a16d4e00d355dda5f') }}
                      </div>
                      <el-select v-model="filterValue.activityType">
                        <el-option
                          v-for="(item, index) in typeList"
                          :key="index"
                          :label="item.label"
                          :value="item.command" />
                      </el-select>
                    </div>
                  </template>
                  <div class="filter-item">
                    <div class="filter-item__label">
                      {{ $t('crm.components.08413ab20c635da9436123defe13ebbc') }}
                    </div>
                    <time-type-select
                      :options="timeOptions"
                      :default-type="filterValue.timeLine"
                      @change="timeTypeChange" />
                  </div>
                </div>
                <flexbox
                  align="center"
                  justify="flex-end"
                  class="filter-popover__footer">
                  <el-button type="primary" @click="filterSure">
                    {{ $t('crm.components.fd290eabb4b74dc9c62ae97db26f65f1') }}
                  </el-button>
                  <el-button @click="filterPopoverVisible = false">
                    {{ $t('crm.components.70144b4656fbac2a7d0f3ca6df74ca40') }}
                  </el-button>
                </flexbox>
              </div>
              <el-button
                slot="reference"
                :type="filterPopoverVisible ? 'selected' : 'subtle'"
                size="medium"
                icon="wk wk-screening">
                {{ $t('crm.components.1398cbf2f221bde45729264257e62eb3') }}
              </el-button>
            </el-popover>
          </flexbox-item>
        </flexbox>

        <div>
          <flexbox
            v-for="(children, index) in list"
            :key="children.time"
            align="stretch"
            class="log-group">
            <div class="log-group__title">
              <div class="time-day">{{ getSectionDay(children.time) }}</div>
              <div class="time-month">{{ getSectionMonth(children.time) }}</div>
            </div>

            <flexbox-item class="log-group__body">
              <log-cell
                v-for="(item, itemIndex) in children.list"
                :key="itemIndex"
                :section="index"
                :index="itemIndex"
                :item="item"
                :can-delete="!isSeas"
                :crm-type="crmType"
                :show-control="filterValue.queryType === 1"
                @delete="logCellDelete"
                @edit="logCellEdit"
                @crm-detail="checkCRMDetail">
                <activity-item
                  v-if="isObject(item.content) && item.type != 4"
                  slot="content"
                  :item-data="item"
                  @detail="checkCRMDetail" />
              </log-cell>
            </flexbox-item>
          </flexbox>
        </div>
        <p ref="scrollBottomTips" class="scroll-bottom-tips">
          {{ loading ? $t('crm.components.d623855fcb15d9cc22b4db64cd1b1613') : noMore ? $t('crm.components.f3abfd15a010870d7843efff3c312538') : $t('crm.components.885de63d82dc53bd0c5f2f6d47e3b2ca') }}
        </p>
      </div>
    </div>

    <!-- CRM详情 -->
    <c-r-m-full-screen-detail
      :id="relationID"
      :visible.sync="showFullDetail"
      :crm-type="relationCrmType" />

    <!-- 跟进记录编辑 -->
    <log-edit-dialog
      v-if="logEditDialogVisible"
      :visible.sync="logEditDialogVisible"
      :data="logEditData"
      :crm-relative-props="crmRelativeProps"
      @save="logEditSave"
    />
  </div>
</template>

<script>
import {
  crmActivityListAPI,
  crmActivityAddAPI
} from '@/api/crm/common'
import { crmCustomerQuerySuperiorIdsAPI } from '@/api/crm/customer'

import LogAdd from './LogAdd'
import LogCell from './LogCell'
import LogEditDialog from './LogEditDialog'
import crmTypeModel from '@/views/crm/model/crmTypeModel'
import ActivityItem from './ActivityItem'

import XrSystemIconMixin from '@/mixins/XrSystemIcon'
import ActivityTypeMixin from './ActivityType'
import TimeTypeSelect from '@/components/TimeTypeSelect'
import { debounce } from 'throttle-debounce'
import { mapGetters } from 'vuex'
import moment from 'moment'
import { isEleVisible } from '@/utils'
import { isObject } from '@/utils/types'

export default {
  name: 'Activity', // 活动
  components: {
    LogAdd,
    LogCell,
    TimeTypeSelect,
    LogEditDialog,
    CRMFullScreenDetail: () =>
      import('@/components/CRMFullScreenDetail'),
    ActivityItem
  },
  mixins: [XrSystemIconMixin, ActivityTypeMixin],
  inject: ['rootTabs'],
  props: {
    // 模块ID
    id: [String, Number],
    // 首要联系人ID
    // contactsId: [String, Number],
    // 没有值就是全部类型 有值就是当个类型
    crmType: {
      type: String,
      default: ''
    },
    // 是公海 默认是客户
    isSeas: {
      type: Boolean,
      default: false
    },
    // 筛选数据源
    typeList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 详情
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      // 筛选
      isSearchRequest: false,
      filterValue: {},
      filterPopoverForm: {},
      timeOptions: [
        { label: this.$t('crm.components.bbfd15ea5cfbd57828dcc189a28d948e'), value: '' },
        { label: this.$t('crm.components.a91b095b945591e559bb5b2a81a6c9a1'), value: '7' },
        { label: this.$t('crm.components.3d02f41652f8820913c08ae81a16d132'), value: '30' },
        { label: this.$t('crm.components.6958aaa3873a4a3389ce9e64d06b619a'), value: '60' }
      ],
      // 筛选 popover
      filterPopoverVisible: false,

      // 活动列表
      list: [],
      noMore: false,
      page: 1,
      // CRM详情
      showFullDetail: false, // 查看相关客户管理详情
      relationID: '', // 相关ID参数
      relationCrmType: '', // 相关类型
      // scrollKey: Date.now(),
      // 跟进记录编辑
      sendLoading: false,
      logEditData: null,
      logEditPosition: {
        seciton: 0,
        index: 0
      },
      logEditDialogVisible: false,
      // 上下级ids
      superiorIds: []
    }
  },
  computed: {
    ...mapGetters(['crm']),

    typeName() {
      return crmTypeModel.keyToNameData[this.crmType]
    },

    /**
     * 是否有跟进记录的权限
     */
    showRecord() {
      return this.crm && this.crm.followRecord && this.crm.followRecord.read
    },

    // 是否能新建跟进记录
    canCreateFollowRecord() {
      return this.crm && this.crm.followRecord && this.crm.followRecord.save
    },

    scrollDisabled() {
      return this.loading || this.noMore
    },

    // 用于弹框筛选
    crmRelativeProps() {
      const types = [
        'customer',
        'contacts',
        'business',
        'contract',
        'receivables'
      ]
      const obj = {}
      types.forEach(key => {
        const searchList = []
        const values = this.detail && this.detail.customerId ? [this.detail.customerId] : []
        if (key === 'customer') {
          searchList.push({
            type: 11,
            values: this.superiorIds
          })
        } else {
          searchList.push({
            formType: 'text',
            name: 'customer_id',
            type: 1,
            values
          })
        }

        obj[key] = {
          searchList
        }
      })

      return {
        paramsObj: obj
      }
    }
  },

  watch: {
    id() {
      this.initInfo()
      this.refreshLogList()
    }
  },
  created() {
    this.debouncedRefreshLogList = debounce(300, this.refreshLogList)
    this.initInfo()
    this.getSuperiorIds()
  },
  mounted() {
    this.refreshLogList()
  },
  methods: {
    /**
     * @description: 获取上下级ids
     * @return {*}
     */
    getSuperiorIds() {
      const customerId = this.detail.customerId
      if (typeof customerId === 'string' &&
      customerId.length > 10 // 线索详情会有一个初始化0的客户id ，忽略掉。
      ) {
        crmCustomerQuerySuperiorIdsAPI(customerId).then(res => {
          console.log(res)
          this.superiorIds = res.data || []
        }).catch(() => {

        })
      }
    },

    /**
     * @description: 判断是否是对象
     * @param {*} data
     * @return {*}
     */
    isObject(data) {
      return isObject(data)
    },

    /**
     * 父容器滚动
     */
    scroll() {
      const scrollBottomTips = this.$refs.scrollBottomTips
      if (isEleVisible(scrollBottomTips) && !this.noMore) {
        this.getLogList()
      }
    },

    /**
     * 发布日志
     */
    sendLog(data) {
      const params = { ...data }
      params.activityType = crmTypeModel[this.crmType]
      params.activityTypeId = this.id
      if (['contacts', 'contract'].includes(this.crmType)) {
        params.titleName = this.detail.name
      } else {
        params.titleName = this.detail[`${this.crmType}Name`]
      }

      this.sendLoading = true
      crmActivityAddAPI(params)
        .then(res => {
          this.sendLoading = false
          this.$message.success(this.$t('crm.components.e08e8c922cceb84a5586b36335443b6f'))
          // 重置页面
          if (this.$refs.logAdd) {
            this.$refs.logAdd.resetInfo()
          }
          // 如果有下次联系时间，更新详情
          if (params.nextTime) {
            this.$emit('update-detail')
          }
          this.refreshLogList()
        })
        .catch(() => {
          this.sendLoading = false
        })
    },

    /**
     * 初始化信息
     */
    initInfo() {
      this.$nextTick(() => {
        if (this.$refs.logAdd) {
          this.$refs.logAdd.resetInfo()
        }
      })
      // recordType 1 跟进记录 2 创建记录 3 阶段变更 4 外勤签到
      // queryType 1 跟进记录、外勤签到 2 活动记录
      this.filterValue = {
        search: '',
        queryType: this.showRecord ? 1 : 2,
        timeLine: {
          label: this.$t('crm.components.d12706e9a6796ed2aed08548a06aa7b4'),
          value: ''
        }
      }
    },

    /**
     * 初始化日志
     */
    refreshLogList(isSearchRequest) {
      this.isSearchRequest = isSearchRequest || false
      this.page = 1
      this.noMore = false
      this.list = []
      this.filterPopoverVisible = false
      this.getLogList()
    },

    /**
     * 活动筛选
     */
    handleSelectClick(value) {
      this.filterValue.queryType = value
      this.refreshLogList()
    },

    /**
     * 时间筛选
     */
    timeTypeChange(data) {
      this.filterValue.timeLine = data
    },

    /**
     * 筛选确定
     */
    filterSure() {
      const { type, startTime, endTime } = this.filterValue.timeLine
      if (type === 'custom') {
        const days = moment(endTime.replace(/\./g, '-')).diff(moment(startTime.replace(/\./g, '-')), 'days', true)
        if (days > 90) {
          this.$message.error(this.$t('crm.components.4cbe6276642a442af2baab3203a07f69'))
          return
        }
      }
      this.refreshLogList()
    },

    /**
     * 获取筛选请求参数
     * @return {*}
     */
    getFilterParams() {
      const params = {
        page: this.page,
        crmType: crmTypeModel[this.crmType], // 9是公海
        activityTypeId: this.id,
        activityType: this.filterValue.activityType
      }

      if (this.filterValue.queryType) {
        params.queryType = this.filterValue.queryType
      }

      if (this.filterValue.search) {
        params.content = this.filterValue.search
      }

      if (this.filterValue.timeLine.type) {
        if (this.filterValue.timeLine.type === 'custom') {
          params.dateFilter = 'custom'
          params.startDate = this.filterValue.timeLine.startTime.replace(/\./g, '-')
          params.endDate = this.filterValue.timeLine.endTime.replace(/\./g, '-')
        } else {
          const intervalDay = this.filterValue.timeLine.value
          params.dateFilter = {
            7: 'previous7day',
            30: 'previous30day',
            60: 'previous60day'
          }[intervalDay] || ''
        }
      }

      return params
    },

    /**
     * 活动日志
     */
    getLogList() {
      this.loading = true
      const params = this.getFilterParams()
      crmActivityListAPI(params)
        .then(res => {
          this.loading = false
          if (!this.noMore) {
            this.page++
            this.formatList(res.data.list)
          }
          this.noMore = res.data.lastPage

          // 如果还有更多
          if (!this.noMore) {
            this.$nextTick(() => {
              this.scroll()
            })
          }

          if (this.isSearchRequest) {
            this.$nextTick(() => {
              this.$refs.activitySearchInput.focus()
            })
          }
        })
        .catch(() => {
          this.noMore = true
          this.loading = false
        })
    },

    /**
     * 把获取到的列表数据按照时间分组
     * @param list
     */
    formatList(list) {
      let last = this.list[this.list.length - 1] || null
      list.forEach(item => {
        // 将详情创建人传进去
        item.currentInfoCreateUser = this.detail.createUserId
        const createTime = moment(item.createTime).format('YYYY-MM-DD')
        if (last && last.time === createTime) {
          this.list[this.list.length - 1].list.push(item)
        } else {
          this.list.push({
            time: createTime,
            list: [item]
          })
          last = this.list[this.list.length - 1]
        }
      })
    },

    /**
     * 跟进日志查看详情
     */
    checkCRMDetail(type, id) {
      if (!!type && !!id) {
        this.relationID = id
        this.relationCrmType = type
        this.showFullDetail = true
      }
    },

    getActivityIcon(activityType) {
      // 1 线索 2 客户 3 联系人 4 产品 5 商机 6 合同 7 回款 8 日志 9 审批 10 日程 11 任务 12 发邮件
      return this.getXrIcon(this.getActivityType(activityType))
    },

    getActivityTypeColor(activityType) {
      // 1 线索 2 客户 3 联系人 4 产品 5 商机 6 合同 7 回款 8 日志 9 审批 10 日程 11 任务 12 发邮件
      return this.getXrIconColor(this.getActivityType(activityType))
    },

    /**
     * 跟进日志删除
     */
    logCellDelete(data, index, seciton) {
      this.list[seciton].list.splice(index, 1)
      if (this.list[seciton].list.length == 0) {
        this.list.splice(seciton, 1)
      }
      // this.scrollKey = Date.now()
      this.refreshLogList()
    },

    /**
     * 跟进日志编辑
     */
    logCellEdit(data, index, seciton) {
      this.logEditData = data
      this.logEditPosition = {
        seciton,
        index
      }
      this.logEditDialogVisible = true
    },

    logEditSave(data) {
      if (!data) {
        this.refreshLogList()
      } else if (data && this.logEditPosition.seciton >= 0 && this.logEditPosition.index >= 0) {
        this.list[this.logEditPosition.seciton].list.splice(this.logEditPosition.index, 1, data)
      }
    },

    /**
     * 获取section 时间
     */
    getSectionDay(time) {
      return moment(time).format('DD')
    },

    getSectionMonth(time) {
      return moment(time).format('YYYY.MM')
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  height: 100%;
  margin-bottom: 240px;
}

.log.is-top {
  margin-top: 0;
}

.log {
  position: relative;
  margin-top: #{$--interval-base * 5};

  &__filter {
    width: 100%;
    height: 40px;

    .filter-left {
      width: unset;
    }

    .filter-right {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }

  .log-group {
    margin-top: 15px;

    .log-group__title {
      width: 70px;
      padding-top: 15px;
      margin-right: 15px;
      text-align: center;

      .time-day {
        font-size: $--font-size-xxlarge;
      }

      .time-month {
        margin-top: 5px;
        font-size: $--font-size-base;
      }
    }

    .log-group__body {
      .user {}
    }
  }
}

.activity-cell {
  padding: #{$--interval-base / 2} #{$--interval-base * 2} #{$--interval-base * 2 + 1};

  &__label {
    color: $--color-text-secondary;
  }

  &__content {
    color: $--color-primary;
    cursor: pointer;
  }

  &__content:hover {
    text-decoration: underline;
  }

  &.is-paragraph {
    padding-top: 0;
    line-height: 1.5;
  }
}

.el-dropdown-link {
  cursor: pointer;

  .el-icon--right {
    font-weight: bold;
  }
}

.filter-popover {
  padding: 20px 15px;

  &__body {
    .filter-item {
      margin-bottom: 25px;

      .filter-item__label {
        margin-bottom: 5px;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}

::v-deep .time-type-select {
  .type-select {
    width: 100% !important;
  }
}
</style>
